package io.nutz.nutzsite.module.sys.controllers;

import io.nutz.nutzsite.common.base.Result;
import io.nutz.nutzsite.common.exception.ErrorException;
import io.nutz.nutzsite.common.utils.DateUtils;
import io.nutz.nutzsite.common.utils.ShiroUtils;
import io.nutz.nutzsite.common.utils.excel.ExcelUtil;
import io.nutz.nutzsite.common.utils.excel.ExportExcel;
import io.nutz.nutzsite.module.sys.models.Role;
import io.nutz.nutzsite.module.sys.models.User;
import io.nutz.nutzsite.module.sys.models.Zfxs;
import io.nutz.nutzsite.module.sys.services.RoleService;
import io.nutz.nutzsite.module.sys.services.UserService;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.Sqls;
import org.nutz.dao.util.DaoUp;
import org.nutz.dao.util.cri.SqlExpressionGroup;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Lang;
import org.nutz.lang.Strings;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.annotation.AdaptBy;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.POST;
import org.nutz.mvc.annotation.Param;
import org.nutz.mvc.upload.TempFile;
import org.nutz.mvc.upload.UploadAdaptor;
import org.nutz.plugins.slog.annotation.Slog;
import org.nutz.plugins.validation.Errors;

/**
 * 用户 信息操作处理
 *
 * @author haiming
 * @date 2019-04-12
 */
@IocBean
@At("/sys/user")
public class UserController {
    private static final Log log = Logs.get();

    @Inject
    private UserService userService;

    @Inject
    private RoleService roleService;
    

    @RequiresPermissions("sys:user:view")
    @At("")
    @Ok("th:/sys/user/user.html")
    public void index(HttpServletRequest req) {

    }

    /**
     * 查询用户列表
     */
    @At
    @Ok("json")
    public Object list(@Param("pageNum")Integer pageNum,
                       @Param("pageSize")Integer pageSize,
                       @Param("deptId") String deptId,//用户管理，选择部门时
                       /*@Param("loginName") String loginName,
                       @Param("phonenumber") String phonenumber,
                       @Param("beginTime") Date beginTime,
                       @Param("endTime") Date endTime,*/
                       @Param("id") String id,//用户查询
                       @Param("orderByColumn") String orderByColumn,
                       @Param("isAsc") String isAsc,
                       HttpServletRequest req) {
        Cnd cnd = Cnd.NEW();
        if (!Strings.isBlank(id)) {
        	SqlExpressionGroup e=Cnd.exps("id", "like", "%" + id + "%").or("user_name", "like", "%" + id + "%");
            cnd.and(e);
        }
        if (!Strings.isBlank(deptId)) {
            cnd.and("deptId", "=", deptId);
        }
        cnd.and("id","!=","adminLrw");
        return userService.tableList(pageNum, pageSize, cnd, orderByColumn, isAsc, "dept");
    }

    /**
     * 新增用户
     */
    @At("/add")
    @Ok("th:/sys/user/add.html")
    public void add(HttpServletRequest req) {
        List<Role> roles = roleService.query(Cnd.where("status", "=", false).and("del_flag", "=", false));
        req.setAttribute("roles", roles);
    }

    /**
     * 新增保存用户
     */
    @RequiresPermissions("sys:user:add")
    @At
    @POST
    @Ok("json")
    @Slog(tag = "用户管理", after = "新增保存用户管理id=${args[0].id}")
    public Object addDo(@Param("..") User user,  HttpServletRequest req) {
        try {
            /*if (es.hasError()) {Errors es,
                 return Result.error(es);
            }*/
            userService.insert(user);
            return Result.success("system.success");
        } catch (Exception e) {
        	log.debug(e.getMessage());
            return Result.error(e instanceof ErrorException ? e.getMessage() : "system.error");
        }
    }

    /**
     * 修改用户
     */
    @At("/edit/?")
    @Ok("th://sys/user/edit.html")
    public void edit(String id, HttpServletRequest req) {
        User user = userService.fetch(id);
        userService.fetchLinks(user, "dept|roles");
        List<Role> roles = roleService.query(Cnd.where("status", "=", false).and("del_flag", "=", false));
        roles.forEach(role -> {
            if (user.getRoles() != null && user.getRoles().size() > 0) {
//				System.out.println(user.getRoles().contains(role));
                role.setFlag(user.getRoles().contains(role));
            }
        });
        req.setAttribute("user", user);
        req.setAttribute("roles", roles);
    }

    /**
     * 修改保存用户
     */
    @RequiresPermissions("sys:user:edit")
    @At
    @POST
    @Ok("json")
    @Slog(tag = "用户管理", after = "修改保存用户管理")
    public Object editDo(@Param("..") User user, HttpServletRequest req) {
        try {
//            if (es.hasError()) {, Errors es
//                 return Result.error(es);
//            }
            if (Lang.isNotEmpty(user)) {
                userService.update(user);
            }
            return Result.success("system.success");
        } catch (Exception e) {
            return Result.error(e instanceof ErrorException ? e.getMessage() : "system.error");
        }
    }

    /**
     * 删除用户
     */
    @At("/remove")
    @Ok("json")
    @RequiresPermissions("sys:user:remove")
    @Slog(tag = "用户管理", after = "删除用户:${array2str(args[0])}")
    public Object remove(@Param("ids") String[] ids, HttpServletRequest req) {
        try {
            userService.delete(ids);
            return Result.success("system.success");
        } catch (Exception e) {
            return Result.error("system.error");
        }
    }

    @At("/resetPwd/?")
    @Ok("th:/sys/user/resetPwd.html")
    public void resetPwd(String id, HttpServletRequest req) {
        User user = userService.fetch(id);
        req.setAttribute("user", user);
    }

    @At
    @POST
    @Ok("json")
    @RequiresPermissions("sys:user:resetPwd")
    @Slog(tag = "用户管理", after = "重置密码")
    public Object resetPwd(@Param("..") User user, HttpServletRequest req) {
        try {
            userService.resetUserPwd(user);
            return Result.success("system.success");
        } catch (Exception e) {
            return Result.error("system.error");
        }
    }

    @At
    @POST
    @Ok("json")
    public Object checkLoginNameUnique(@Param("id") String id, @Param("name") String name, HttpServletRequest req) {
        return userService.checkLoginNameUnique(id);
    }
    @RequiresPermissions("sys:user:export")
    @At
	@Ok("json")
    public Object export(HttpServletRequest req, HttpServletResponse response) {
    	List<User> list = userService.query();//.findList(cnd);
		String fileName = "用户数据" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
		try{
			new ExportExcel("用户数据", User.class).setDataList(list).writeFile(fileName);
		}catch(Exception ex)
		{
			log.error(ex.getMessage());
			return Result.error("导出失败"+ex.getMessage());
		}
		return Result.success(fileName);
    }
    @At
	@Ok("json")
	public Object export2(HttpServletRequest req, HttpServletResponse resp){
		//String fileName = "系统参数"+ DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
		List<User> list =userService.query();
		log.debug("\r\nex2:"+list.size()+"\r\n");
		ExcelUtil<User> util = new ExcelUtil<User>(User.class);
        return util.exportExcel(list, "用户数据");

	}
	/**
	 * 下载导入用户数据模板
	 */
	@RequiresPermissions("sys:user:importTemplate")
	@At
	@Ok("json")
	public Object importTemplate(HttpServletResponse response) {
		List<User> list = userService.query(Cnd.where("id","=","test"));
		list.get(0).setRoleIds("5");
		list.get(0).setPassword("123456");
		list.get(0).setGender("0");
		String fileName = "用户模板数据" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
		try{
			new ExportExcel("用户模板数据", User.class).setDataList(list).writeFile(fileName);
		}catch(Exception ex)
		{
			log.error(ex.getMessage());
			return Result.error("导出失败"+ex.getMessage());
		}
		return Result.success(fileName);
	}

	/**
	 * 导入用户数据
	 */
	@AdaptBy(type = UploadAdaptor.class, args = {"ioc:fileUpload"})
    @POST
	@RequiresPermissions("sys:user:import")
	@At
	@Ok("json")
	public Object importData(@Param("file") TempFile file,@Param("updateSupport")  String updateSupport) {
		try {
			boolean isUpdateSupport = updateSupport=="true"?true:false;
			String message = userService.importData(file, isUpdateSupport);
			return Result.success(message);
		} catch (Exception ex) {
			return Result.error(ex.getMessage());
		}
	}
	@At//
	@POST
	@Ok("json")
	public Object updStu(@Param("year")Integer year,@Param("uids")String uids,HttpServletRequest req)  {		
  	  String r=userService.updStu(year,uids);
  	  if(r.equals("0")) return Result.success("更新成功");
  	  else return Result.error(r);		
	}
	@At//
	@POST
	@Ok("json")
	public Object updTea(HttpServletRequest req)  {		
  	  String r=userService.updTea();
  	  if(r.equals("0")) return Result.success("更新成功");
  	  else return Result.error(r);		
	}
    /**
     * 查询用户列表
     */
    @At
    @Ok("json")
    public Object listjs(@Param("pageNum")Integer pageNum,
                       @Param("pageSize")Integer pageSize,
                       @Param("userName") String userName,
                       @Param("id") String id,//用户查询
                       @Param("orderByColumn") String orderByColumn,
                       @Param("isAsc") String isAsc,
                       HttpServletRequest req) {

        return userService.tableListJs(pageNum, pageSize, userName, id);
    }
}
